<template>
  <div class="page-dialog">
    <el-dialog v-model="isShowDialog" center destroy-on-close width="50%">
      <KiForm v-bind="dialogConfig" v-model="formData">
        <template #footer>
          <div class="footer">
            <el-button @click="isShowDialog = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmClick">确定</el-button>
          </div>
        </template>
      </KiForm>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTableStore } from '@/store';
import { ref, watch } from 'vue';
import KiForm from '../ki-form/KiForm.vue';
import {IForm} from '@/components/ki-form/type'
import {ElMessage} from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
interface IProps {
  dialogConfig:IForm
  tableName:string
  editeData?:any
}
const props = withDefaults(defineProps<IProps>(),{
  editeData:() => ({})
})
const isShowDialog = ref(false)
const changeIsShowDialog = () => {
  isShowDialog.value = !isShowDialog.value
}

const formOrignData:any = {}
const formItems = props.dialogConfig.formItems || []

watch(() => props.editeData,(newValue:any) => {  
  for(const item of formItems){
    formOrignData[`${item.field}`] = newValue[`${item.field}`]
  }
})

const formData = ref(formOrignData)

const tableStore = useTableStore()
const handleConfirmClick = () => {
  if(!Object.keys(props.editeData).length){
    tableStore.createTableAction(props.tableName,{...formData.value})
  }else{
    tableStore.editeTableAction(props.tableName,props.editeData.id,{...formData.value})
  }
  ElMessage.success('成功')
  formData.value = formOrignData
  isShowDialog.value = false
}
defineExpose({
  changeIsShowDialog
})
</script>

<style scoped>
.footer{
  text-align: center;
}
</style>